package com.umfwechat.lightprogram.controller.selfdeploy;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


import com.umfwechat.common.constant.CacheConsts;
import com.umfwechat.util.RedisUtil;
import com.umfwechat.util.ReqMessageUtil;
import com.umfwechat.util.StringReaderUtils;
import com.umfwechat.wx.service.WeixinService;
import com.umpay.operation.xml.XmlData;
import com.umpay.sp.model.common.ReqMessage;
import com.umpay.sp.model.common.ResMessage;
import com.umpay.sp.model.saas.StoreInf;
import com.umpay.sp.service.saas.remote.StoreInfServiceRemote;
import com.umpay.sp.service.sys.remote.UserServiceRemote;

@Controller
@RequestMapping("/merchantDeploy")
public class QrCodeController {
	private static Logger logger = LoggerFactory.getLogger(QrCodeController.class);
	
	//生成二维码service
	@Autowired
	private WeixinService weixinService; 
	//用户信息server
	@Resource
	private UserServiceRemote userServiceRemote_sp;
	@Resource
	private StoreInfServiceRemote storeInfServiceRemote;
	/**
	 * 展示收款人二维码
	 * @param session
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/qrCodeDisplay")
	@ResponseBody
	public JSONObject qrCodeDisplay(HttpServletRequest request, HttpServletResponse response) throws Exception{		
		JSONObject json= new JSONObject();
		json.put("retCode", "0000");
		json.put("retMsg", "成功");
		String reqJSON=  (String) request.getAttribute("_requestData");
//		String reqJSON = null;
//		try {
//			reqJSON = StringReaderUtils.readFromIO(request.getInputStream());
//			logger.info("展示立马付接口入参>>>" + reqJSON);
//		} catch (IOException e) {
//			json.put("retCode", "0001");
//			json.put("retMsg", "展示立马付接口入参获取失败");
//			logger.error("展示立马付接口入参获取异常", e);
//			return json;
//		}
		JSONObject param=JSONObject.fromObject(reqJSON);
		String storeId = param.optString("storeId");	//店铺编号
		Integer scene_id=null;
		String values=null;
		try {
			values = RedisUtil.get(CacheConsts.REDIS_QRCODE+storeId);
			logger.info("redis中获取到的值为"+values);
		} catch (Exception e) {
			json.put("retCode", "0001");
			json.put("retMsg", "二维码缓存信息获取异常，请稍后重试");
			logger.info("二维码缓存信息获取异常："+e);
			return json;
		}
		if(values==null){
			//先查询店铺详细信息，绑定收款码时使用店铺名称
			ReqMessage reqStore = ReqMessageUtil.makeSpReq();
			reqStore.put("storeId", storeId);
			ResMessage resStore =null;
			try {
				resStore = storeInfServiceRemote.getStoreInfByPri(reqStore);
			} catch (Exception e1) {
				json.put("retCode", "0001");
				json.put("retMsg","查询店铺详情接口异常");
				logger.info("查询店铺详情接口异常："+e1);
				return json;
			}
			String retCodeStore = resStore.getRetCode();
			StoreInf storeInf =null;
			if(retCodeStore.equals("0000")){
				storeInf = (StoreInf) resStore.getResMap().get("storeInf");
				if(storeInf==null){
					json.put("retCode", "0001");
					json.put("retMsg", "查询店铺详情没有查询到");
					return json;
				}
			}else{
				json.put("retCode", "0001");
				json.put("retMsg", "查询店铺详情没有查询到"+resStore.getRetMsg());
				return json;
			}
			logger.info("根据店铺编号查询出来的店铺信息为"+storeInf.toString());
//			-----------------------------------------------
			//如果查询不到，就去数据库中获取
			ReqMessage reqUser = ReqMessageUtil.makeSpReq();
			reqUser.put("merFlag", storeInf.getMerId());
			reqUser.put("currentPage", "1");
			reqUser.put("pageSize", "4");
			ResMessage resUser =null;
			try {
				resUser = userServiceRemote_sp.queryList(reqUser);
			} catch (Exception e) {
				json.put("retCode", "0001");
				json.put("retMsg","根据店铺编号查询用户接口异常");
				logger.info("根据店铺编号查询用户接口异常："+e);
				return json;
			}
			String retCodeUser = resUser.getRetCode();
			if(retCodeUser.equals("0000")){
				List<Map<String, Object>> resultList=(List<Map<String, Object>>)resUser.getResMap().get(XmlData.RESULT_LIST);
				if(resultList.size()==0){
					json.put("retCode", "0001");
					json.put("retMsg","根据店铺编号查询用户接口失败"+resUser.getRetMsg());
					return json;
				}else{
					logger.info("查询出来的用户信息为"+resultList.toString());
					Map<String, Object> resultmap = resultList.get(0);
					scene_id=(Integer)resultmap.get("userId");
					String expireTime="86400";//24小时
					String qrCodeUrl;
					try {
						qrCodeUrl = weixinService.getTicketQrCode(expireTime,scene_id);
					} catch (Exception e) {
						json.put("retCode", "0001");
						json.put("retMsg", "获取二维码异常，稍后重试");
						logger.info("获取二维码异常："+e);
						return json;
					}
					json.put("qrCodeUrl", qrCodeUrl);
					StringBuffer sb = new StringBuffer();
					long currentTime = new Date().getTime();
					sb.append(scene_id).append(",").append(expireTime).append(",").append(String.valueOf(currentTime)).append(",").append(qrCodeUrl);
					RedisUtil.set(CacheConsts.REDIS_QRCODE+storeId, 2592000, sb.toString());	//缓存起来,缓存30天
					json.put("storeId", storeId);
					return json;
				}
			}else{
				json.put("retCode", "0001");
				json.put("retMsg",resUser.getRetMsg());
				return json;
			}
		}else{
			String[] value= values.split(",");
			String userId = value[0];	//收款人id
			String time = value[1];		//有效期
			String createTime = value[2];	//创建时间
			String url = value[3];	//二维码url
			long date1=Long.valueOf(createTime);
			long s = (new Date().getTime()-date1)/1000;	
			Long s0 = Long.valueOf(time);
			//判断缓存中二维码是否过期
			if(s<s0){	//如果没有过期就直接将二维码url返回
				json.put("qrCodeUrl", url);
			}else{
				//如果过期，就重新生成一个新的二维码
				scene_id=Integer.valueOf(userId);
				String expireTime="86400";//24小时
				String qrCodeUrl;
				try {
					qrCodeUrl = weixinService.getTicketQrCode(expireTime,scene_id);
				} catch (Exception e) {
					json.put("retCode", "0001");
					json.put("retMsg", "获取二维码异常，稍后重试");
					logger.info("获取二维码异常："+e);
					return json;
				}
				json.put("qrCodeUrl", qrCodeUrl);
				StringBuffer sb = new StringBuffer();
				long currentTime = new Date().getTime();
				sb.append(userId).append(",").append(expireTime).append(",").append(String.valueOf(currentTime)).append(",").append(qrCodeUrl);
				RedisUtil.set(CacheConsts.REDIS_QRCODE+storeId, 2592000, sb.toString());	//缓存起来,缓存30天
			}
			json.put("storeId", storeId);
			return json;
		}
		
	}
}
